package com.maxlen.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.maxlen.common.rabbitMQConstant.OrderRabbitMQConstant;
import com.maxlen.common.utils.*;
import com.maxlen.order.config.AlipayTemplate;
import com.maxlen.order.constant.OrderConstant;
import com.maxlen.order.dao.OrderDao;
import com.maxlen.order.entity.OrderEntity;
import com.maxlen.order.entity.OrderItemEntity;
import com.maxlen.order.entity.dto.OrderSubmitDTO;
import com.maxlen.order.entity.to.*;
import com.maxlen.order.entity.vo.*;
import com.maxlen.order.enume.OrderDeleteStatusEnum;
import com.maxlen.order.enume.OrderStatusEnum;
import com.maxlen.order.exception.NotStockException;
import com.maxlen.order.feign.*;
import com.maxlen.order.interceptor.LoginInterceptor;
import com.maxlen.order.service.OrderItemService;
import com.maxlen.order.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
//@RabbitListener(queues = {"hello-java-queue"})
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GoodsFeignService goodsFeignService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        System.out.println(params);
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        Object status = params.get("status");
        if(status != null) {
            wrapper.eq(OrderEntity::getStatus, status);
        }
        Object key = params.get("key");
        if(key != null) {
            wrapper.like(OrderEntity::getId, key).or()
                    .like(OrderEntity::getOrderSn, key).or()
                    .like(OrderEntity::getMemberUsername, key).or()
                    .like(OrderEntity::getMemberId, key);
        }
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                wrapper.orderByDesc(OrderEntity::getCreateTime)
        );

        return new PageUtils(page);
    }

    /**
     * 回显页面的结算页面
     * @return
     */
    @Override
    public R confirmOrder() {
        OrderConfirmVO confirmVO = new OrderConfirmVO();
        LoginInfoTO loginInfoTO = LoginInterceptor.threadLocalID.get();
        LoginInterceptor.threadLocalID.remove();

        try{
            // 获取用户地址信息
            CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
                R address = memberFeignService.getAddress(loginInfoTO.getMemberId());
                if (!address.isOk()) {
                    throw new RuntimeException();
                }
                confirmVO.setAddress(address.getData(new TypeReference<List<FareVO.MemberAddressVO>>() {}));
            }, threadPoolExecutor);

            // 计算购物车选中商品的总价格
            CompletableFuture<Void> itemFuture = CompletableFuture.runAsync(() -> {
                R currentUserCartItemByCheck = cartFeignService.currentUserCartItemByCheck(loginInfoTO.getMemberId());
                if (!currentUserCartItemByCheck.isOk()) {
                    throw new RuntimeException();
                }
                List<OrderConfirmVO.CartItemVO> list = currentUserCartItemByCheck.getData(new TypeReference<List<OrderConfirmVO.CartItemVO>>() {});

                // 获取秒杀商品
                List<Long> skuIds = list.stream().map(OrderConfirmVO.CartItemVO::getSkuId).collect(Collectors.toList());
                try {
                    R skuSeckillBySkuIdList = seckillFeignService.getSkuSeckillBySkuIdList(skuIds);
                    List<SeckillPriceTO> data = skuSeckillBySkuIdList.getData(new TypeReference<List<SeckillPriceTO>>() {});
                    for (OrderConfirmVO.CartItemVO cartItemVO : list) {
                        for (SeckillPriceTO datum : data) {
                            if(cartItemVO.getSkuId().equals(datum.getSkuId())) {
                                BigDecimal bigDecimal = datum.getPrice();
                                if(bigDecimal != null && bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                                    cartItemVO.setSeckillPrice(cartItemVO.getSkuPrice().subtract(bigDecimal));
                                    int i = datum.getCount() - cartItemVO.getCount();
                                    if(i <= 0) {
                                        cartItemVO.setSeckillCount(datum.getCount());
                                        cartItemVO.setCount(cartItemVO.getCount() - datum.getCount());
                                    } else {
                                        cartItemVO.setSeckillCount(cartItemVO.getCount());
                                        cartItemVO.setCount(0);
                                    }
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    throw new RuntimeException("库存系统异常");
                }

                confirmVO.setItems(list);

                // 判断商品有货还是无货
                List<Long> skuIdList = confirmVO.getItems().stream().map((OrderConfirmVO.CartItemVO::getSkuId)).collect(Collectors.toList());
                R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
                if(!skuHasStock.isOk()){
                    throw new RuntimeException();
                }
                List<SkuHasStockVO> data = skuHasStock.getData(new TypeReference<List<SkuHasStockVO>>() {});
                Map<Long, Long> map = data.stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));
                for (OrderConfirmVO.CartItemVO item : confirmVO.getItems()) {
                    if(map.get(item.getSkuId()) != null && map.get(item.getSkuId()) > 0L){
                        item.setHasStock(true);
                    }else{
                        item.setHasStock(false);
                    }
                }

                // 获取所有有货的商品的价格总和
                BigDecimal totalPrice = new BigDecimal("0");
                for (OrderConfirmVO.CartItemVO cartItemVO : confirmVO.getItems()) {
                    if(cartItemVO.getHasStock()){
                        BigDecimal multiply = cartItemVO.getSkuPrice().multiply(new BigDecimal(cartItemVO.getCount()));
                        BigDecimal seckillMultiply = new BigDecimal("0");
                        if(cartItemVO.getSeckillPrice() != null && cartItemVO.getSeckillCount() != null) {
                            seckillMultiply = cartItemVO.getSeckillPrice()
                                    .multiply(new BigDecimal(cartItemVO.getSeckillCount()));
                        }
                        totalPrice = totalPrice.add(multiply).add(seckillMultiply);
                    }
                }
                confirmVO.setTotalPrice(totalPrice);
                confirmVO.setPayPrice(totalPrice);
            }, threadPoolExecutor);

            // 获取用户的积分
            CompletableFuture<Void> integrationFuture = CompletableFuture.runAsync(() -> {
                R memberIntegration = memberFeignService.getMemberIntegration(loginInfoTO.getMemberId());
                if (!memberIntegration.isOk()) {
                    throw new RuntimeException();
                }
                confirmVO.setIntegration(memberIntegration.getData(new TypeReference<Integer>() {}));
            }, threadPoolExecutor);

            // 防重令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginInfoTO.getMemberId(), token, 30, TimeUnit.MINUTES);
            confirmVO.setOrderToken(token);

            CompletableFuture.allOf(addressFuture, itemFuture, integrationFuture).get();

            return R.ok().setData(confirmVO);

        } catch (ExecutionException | InterruptedException e) {
            return R.error();
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 生成订单
     * @param orderSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public R setSubmitOrder(OrderSubmitDTO orderSubmitDTO) {
        System.out.println(orderSubmitDTO);

        LoginInfoTO loginInfoTO = LoginInterceptor.threadLocalID.get();
        LoginInterceptor.threadLocalID.remove();

        // 防止重复生成订单
        String orderToken = orderSubmitDTO.getOrderToken();
        String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginInfoTO.getMemberId()), orderToken);
        if(execute == null || execute.equals(0L)){
            return R.error(ResultCode.SMS_CODE_ERROR);
        }

        String timeId = IdWorker.getTimeId();

        // 优惠券服务参数
        SkuInfoAndCartItemTO skuInfoAndCartItemTO = new SkuInfoAndCartItemTO();
        skuInfoAndCartItemTO.setMemberId(loginInfoTO.getMemberId());
        skuInfoAndCartItemTO.setCouponId(orderSubmitDTO.getCouponId());

        // 生成订单商品
        List<OrderItemEntity> orderItemEntityList = createOrderItem(timeId, loginInfoTO, skuInfoAndCartItemTO);

        // 获取优惠金额
        R orderCouponPrice = couponFeignService.getOrderCouponPrice(skuInfoAndCartItemTO);
        if(!orderCouponPrice.isOk()){
            return null;
        }
        CouponIdListWithPriceTO couponIdListWithPriceTO = orderCouponPrice.getData(new TypeReference<CouponIdListWithPriceTO>() {});

        // 生成订单
        OrderEntity orderEntity = createOrder(timeId, orderSubmitDTO, loginInfoTO, orderItemEntityList, couponIdListWithPriceTO);

        if(ObjectUtils.isEmpty(orderEntity) || ObjectUtils.isEmpty(orderItemEntityList)){
            return R.error(ResultCode.CREATE_ORDER_ERROR);
        }

        OrderCreateTO orderCreateTO = new OrderCreateTO();
        orderCreateTO.setOrder(orderEntity);
        orderCreateTO.setOrderItemEntityList(orderItemEntityList);

        // 添加订单
        List<WareSkuLockTO.LockStockCountTO> lockStockCountTOList = insertOrder(orderEntity, orderItemEntityList);
        WareSkuLockTO wareSkuLockTO = new WareSkuLockTO();
        wareSkuLockTO.setLockStockCountTOList(lockStockCountTOList);
        wareSkuLockTO.setOrderSn(orderEntity.getOrderSn());

        // 锁定库存
        R lockStock = wareFeignService.lockStock(wareSkuLockTO);
        if(!lockStock.isOk()){
            String skuId = lockStock.getMsg();
            if(StringUtils.hasText(skuId)){
                String skuName = null;
                for (OrderItemEntity orderItemEntity : orderItemEntityList) {
                    if(orderItemEntity.getSkuId().equals(Long.valueOf(skuId))){
                        skuName = orderItemEntity.getSkuName();
                    }
                }
                throw new NotStockException(skuName);
            }else{
                throw new NotStockException("错误");
            }
        }

        // 锁定优惠券
        CouponLockTO couponLockTO = new CouponLockTO();
        couponLockTO.setMemberId(loginInfoTO.getMemberId());
        couponLockTO.setOrderSn(timeId);
        couponLockTO.setRealCouponHistoryIdList(couponIdListWithPriceTO.getRealCouponHistoryIdList());
        R lockCouponByMemberId = couponFeignService.lockCoupon(couponLockTO);
        if(!lockCouponByMemberId.isOk()){
            String msg = lockCouponByMemberId.getMsg();
            throw new NotStockException(msg);
        }

        // 发送给延时队列，30分钟后会取消订单
        rabbitTemplate.convertAndSend(
                OrderRabbitMQConstant.ORDER_EVENT_EXCHANGE,
                OrderRabbitMQConstant.ORDER_ORDER_DELAY_BINDING,
                orderEntity);

        return R.ok().setData(orderCreateTO);

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return baseMapper.selectOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn, orderSn));
    }

    // 关闭过期时间的用户订单
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        // 查询订单状态如果还是待付款状态就将订单状态修改为取消状态
        OrderEntity selectById = baseMapper.selectById(orderEntity.getId());
        OrderEntity order = new OrderEntity();
        if(OrderStatusEnum.CREATE_NEW.getCode().equals(selectById.getStatus())){
            order.setId(selectById.getId());
            order.setStatus(OrderStatusEnum.CANCEL.getCode());
            baseMapper.updateById(order);

            System.out.println("订单关闭......");
            System.out.println("发送至解锁库存服务......");
            System.out.println("发送至返还优惠券服务......");
            rabbitTemplate.convertAndSend(OrderRabbitMQConstant.ORDER_EVENT_EXCHANGE, OrderRabbitMQConstant.SEND_ORDER_RELEASE_OTHER, orderEntity.getOrderSn().getBytes());
        }
    }

    @Override
    public R getOrderTimeByOrderSn(String orderSn) {
        OrderEntity orderEntity = baseMapper.selectOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn, orderSn));
        return R.ok().setData((orderEntity.getCreateTime().getTime() + 10000) - new Date().getTime());
    }

    @Override
    public R ZFBPay(String orderSn) throws AlipayApiException {
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);

        OrderEntity order = new OrderEntity();
        order.setId(orderEntity.getId());
        order.setStatus(OrderStatusEnum.PAYED.getCode());
        baseMapper.updateById(order);

        LoginInfoTO loginInfoTO = LoginInterceptor.threadLocalID.get();
        LoginInterceptor.threadLocalID.remove();

        List<OrderItemEntity> list = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, orderSn));
        List<String> skuIdList = list.stream().map((orderItemEntity -> {
            return orderItemEntity.getSkuId().toString();
        })).collect(Collectors.toList());
        cartFeignService.batchDelCartItemByMember(loginInfoTO.getMemberId().toString(), skuIdList);

        return R.ok();

//        PayVO payVO = new PayVO();
//        payVO.setTotal_amount(orderEntity.getPayAmount().setScale(2, RoundingMode.DOWN).toString());
//        payVO.setOut_trade_no(orderEntity.getOrderSn());
//        payVO.setSubject("MaxLen电商收银");
//        payVO.setBody("");

//        String pay = alipayTemplate.pay(payVO);
//        return R.ok().setData(pay);
    }

    @Override
    public OrderAllVO getOrder(Integer status) throws ExecutionException, InterruptedException {

        OrderAllVO orderAllVO = new OrderAllVO();

        LoginInfoTO loginInfoTO = LoginInterceptor.threadLocalID.get();
        LoginInterceptor.threadLocalID.remove();

        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getMemberId, loginInfoTO.getMemberId());
        wrapper.eq(OrderEntity::getDeleteStatus, OrderDeleteStatusEnum.ON.getCode());
        wrapper.orderByDesc(OrderEntity::getCreateTime);
        if (status != null) {
            wrapper.eq(OrderEntity::getStatus, status);
        }
        List<OrderEntity> orderEntityList = baseMapper.selectList(wrapper);

        if(!ObjectUtils.isEmpty(orderEntityList)){
            List<OrderAllVO.OrderVO> orderVOList = new ArrayList<>();
            List<Long> orderIdList = new ArrayList<>();
            for (OrderEntity orderEntity : orderEntityList) {
                OrderAllVO.OrderVO orderVO = CopyUtils.copy(orderEntity, OrderAllVO.OrderVO.class);
                orderVOList.add(orderVO);
                orderIdList.add(orderEntity.getId());
            }

            List<OrderItemEntity> orderItemEntityList = orderItemService.getOrderItemByOrderIdList(orderIdList);
            for (OrderAllVO.OrderVO orderVO : orderVOList) {
                List<OrderAllVO.OrderItemVO> orderItemVOList = new ArrayList<>();
                for (OrderItemEntity orderItemEntity : orderItemEntityList) {
                    if (orderVO.getOrderSn().equals(orderItemEntity.getOrderSn())) {
                        OrderAllVO.OrderItemVO orderItemVO = CopyUtils.copy(orderItemEntity, OrderAllVO.OrderItemVO.class);
                        orderItemVOList.add(orderItemVO);
                    }
                }
                orderVO.setOrderItemVOS(orderItemVOList);
            }
            orderAllVO.setOrderVOList(orderVOList);
        }

        CompletableFuture<Void> createNewCountFuture = CompletableFuture.runAsync(() -> {
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<OrderEntity>()
                    .eq(OrderEntity::getStatus, OrderStatusEnum.CREATE_NEW.getCode())
                    .eq(OrderEntity::getDeleteStatus, OrderDeleteStatusEnum.ON.getCode()));
            orderAllVO.setCreateNewCount(count);
        }, threadPoolExecutor);

        CompletableFuture<Void> sendCountFuture = CompletableFuture.runAsync(() -> {
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<OrderEntity>()
                    .eq(OrderEntity::getStatus, OrderStatusEnum.SEND.getCode())
                    .eq(OrderEntity::getDeleteStatus, OrderDeleteStatusEnum.ON.getCode()));
            orderAllVO.setSendCount(count);
        }, threadPoolExecutor);

        CompletableFuture<Void> completeCountFuture = CompletableFuture.runAsync(() -> {
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<OrderEntity>()
                    .eq(OrderEntity::getStatus, OrderStatusEnum.COMPLETE.getCode())
                    .eq(OrderEntity::getDeleteStatus, OrderDeleteStatusEnum.ON.getCode()));
            orderAllVO.setCompleteCount(count);
        }, threadPoolExecutor);

        CompletableFuture.allOf(createNewCountFuture, sendCountFuture, completeCountFuture).get();

        return orderAllVO;
    }

    @Override
    public R deleteOrder(String orderSn) {
        LoginInfoTO loginInfoTO = LoginInterceptor.threadLocalID.get();
        if(ObjectUtils.isEmpty(loginInfoTO)){
            return R.error(ResultCode.USER_NOT_LOGIN);
        }
        Long memberId = loginInfoTO.getMemberId();

        OrderEntity orderEntity = baseMapper.selectOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderSn, orderSn)
                .eq(OrderEntity::getMemberId, memberId)
                .select(OrderEntity::getStatus));
        if(ObjectUtils.isEmpty(orderEntity)){
            return R.ok();
        }
        if(OrderStatusEnum.PAYED.getCode().equals(orderEntity.getStatus())){
            return R.error(ResultCode.ORDER_WAIT_SEND);
        }
        if(OrderStatusEnum.SEND.getCode().equals(orderEntity.getStatus())){
            return R.error(ResultCode.ORDER_SEND);
        }

        baseMapper.updateOrderDeleteStatus(orderSn, memberId);
        return R.ok();
    }

    @Override
    public void changeStatus(String id, Integer status) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setId(Long.valueOf(id));
        orderEntity.setStatus(status);
        baseMapper.updateById(orderEntity);
    }

    private List<WareSkuLockTO.LockStockCountTO> insertOrder(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntityList){
        baseMapper.insert(orderEntity);

        List<WareSkuLockTO.LockStockCountTO> lockStockCountTOList = new ArrayList<>();
        WareSkuLockTO.LockStockCountTO lockStockCountTO;
        for (OrderItemEntity orderItemEntity : orderItemEntityList) {
            orderItemEntity.setOrderId(orderEntity.getId());

            lockStockCountTO = new WareSkuLockTO.LockStockCountTO();
            lockStockCountTO.setSkuId(orderItemEntity.getSkuId());
            lockStockCountTO.setCount(orderItemEntity.getSkuQuantity());
            lockStockCountTOList.add(lockStockCountTO);
        }

        orderItemService.saveBatch(orderItemEntityList);

        return lockStockCountTOList;
    }

    /**
     * 创建订单
     * @param timeId 订单号
     * @param orderSubmitDTO 前端提交
     * @param loginInfoTO 登录详情
     * @param orderItemEntityList 订单商品项
     * @param couponIdListWithPriceTO 优惠券金额参数
     * @return
     */
    private OrderEntity createOrder(String timeId, OrderSubmitDTO orderSubmitDTO, LoginInfoTO loginInfoTO, List<OrderItemEntity> orderItemEntityList, CouponIdListWithPriceTO couponIdListWithPriceTO){
        OrderEntity orderEntity = new OrderEntity();

        // 订单号
        orderEntity.setOrderSn(timeId);

        // 收货地址
        R fareByAddressId = wareFeignService.getFareByAddressId(orderSubmitDTO.getAddressId());
        if(!fareByAddressId.isOk()){
            return null;
        }
        FareVO fareVO = fareByAddressId.getData(new TypeReference<FareVO>() {});

        orderEntity.setFreightAmount(fareVO.getFare());
        orderEntity.setReceiverName(fareVO.getAddressVO().getName());
        orderEntity.setReceiverPhone(fareVO.getAddressVO().getPhone());
        orderEntity.setReceiverPostCode(fareVO.getAddressVO().getPostCode());
        orderEntity.setReceiverProvince(fareVO.getAddressVO().getProvince());
        orderEntity.setReceiverCity(fareVO.getAddressVO().getCity());
        orderEntity.setReceiverRegion(fareVO.getAddressVO().getRegion());
        orderEntity.setReceiverDetailAddress(fareVO.getAddressVO().getDetailAddress());
        orderEntity.setNote("default");

        // 用户信息
        orderEntity.setMemberId(loginInfoTO.getMemberId());
        orderEntity.setMemberUsername(loginInfoTO.getMemberName());

        // 优惠券
        orderEntity.setCouponId(null);

        // 订单来源
        orderEntity.setSourceType(0);

        // 支付方式
        orderEntity.setPayType(orderSubmitDTO.getPayType());

        // 订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        // 自动确认收货时间
        orderEntity.setAutoConfirmDay(7);

        // 收货状态
//        orderEntity.setConfirmStatus(OrderConfirmStatusEnum.ON.getCode());

        // 优惠、积分、运费金额
        BigDecimal couponPriceData = couponIdListWithPriceTO.getReturnTotalPrice();
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");

        Integer giftGrowth = 0;
        Integer giftIntegration = 0;

        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal payPrice = new BigDecimal("0");

        // 计算金额和积分
        for (OrderItemEntity orderItemEntity : orderItemEntityList) {
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            giftGrowth += orderItemEntity.getGiftGrowth();
            giftIntegration += orderItemEntity.getGiftIntegration();

            totalPrice = totalPrice.add(orderItemEntity.getRealAmount());
        }

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(couponPriceData);
        orderEntity.setDiscountAmount(promotion.add(integration).add(couponPriceData));

        // 积分信息
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setGrowth(giftGrowth);

        // 订单总额 计算总额 + 运费
        orderEntity.setTotalAmount(totalPrice.add(orderEntity.getFreightAmount()));

        // 应付金额 计算总额 - 优惠券折扣
        orderEntity.setPayAmount(orderEntity.getTotalAmount().subtract(couponPriceData));

        // 删除状态
        orderEntity.setDeleteStatus(0);

        return orderEntity;
    }

    /**
     * 创建订单商品项
     * @param timeId 订单号
     * @param loginInfoTO 登录信息
     * @param skuInfoAndCartItemTO 优惠券服务参数
     * @return
     */
    private List<OrderItemEntity> createOrderItem(String timeId, LoginInfoTO loginInfoTO, SkuInfoAndCartItemTO skuInfoAndCartItemTO){

        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();
        OrderItemEntity orderItemEntity;

        // 获取购物车中选中的商品
        R cartItemList = cartFeignService.currentUserCartItemByCheckWithHasStock(loginInfoTO.getMemberId());
        if(!cartItemList.isOk()){
            return null;
        }
        List<OrderConfirmVO.CartItemVO> cartItemListData = cartItemList.getData(new TypeReference<List<OrderConfirmVO.CartItemVO>>() {});
        // 获取秒杀商品
        List<Long> skuIds = cartItemListData.stream().map(OrderConfirmVO.CartItemVO::getSkuId).collect(Collectors.toList());
        try {
            R skuSeckillBySkuIdList = seckillFeignService.getSkuSeckillBySkuIdList(skuIds);
            List<SeckillPriceTO> data = skuSeckillBySkuIdList.getData(new TypeReference<List<SeckillPriceTO>>() {});
            for (OrderConfirmVO.CartItemVO cartItemVO : cartItemListData) {
                for (SeckillPriceTO datum : data) {
                    if(cartItemVO.getSkuId().equals(datum.getSkuId())) {
                        BigDecimal bigDecimal = datum.getPrice();
                        if(bigDecimal != null && bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                            cartItemVO.setSeckillPrice(cartItemVO.getSkuPrice().subtract(bigDecimal));
                            int i = datum.getCount() - cartItemVO.getCount();
                            if(i <= 0) {
                                cartItemVO.setSeckillCount(datum.getCount());
                            } else {
                                cartItemVO.setSeckillCount(cartItemVO.getCount());
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException("库存系统异常");
        }
        skuInfoAndCartItemTO.setCartItemVOList(cartItemListData);

        // 获取商品详情
        List<Long> longList = cartItemListData.stream().map(OrderConfirmVO.CartItemVO::getSkuId).collect(Collectors.toList());
        R spuBySkuIdList = goodsFeignService.getSpuBySkuIdList(longList);
        if(!spuBySkuIdList.isOk()){
            return null;
        }
        SpuAndSkuTO spuBySkuIdListData = spuBySkuIdList.getData(new TypeReference<SpuAndSkuTO>() {});
        skuInfoAndCartItemTO.setSpuAndSkuTO(spuBySkuIdListData);
        Map<Long, Long> spuAndSku = spuBySkuIdListData.getSkuBySpuIdTO().stream().collect(Collectors.toMap(SpuAndSkuTO.SkuBySpuIdTO::getSkuId, SpuAndSkuTO.SkuBySpuIdTO::getSpuId));

        for (OrderConfirmVO.CartItemVO cartItemVO : cartItemListData) {
            orderItemEntity = new OrderItemEntity();

            // 订单 id
            orderItemEntity.setOrderSn(timeId);

            // spu 信息
            Long spuId = spuAndSku.get(cartItemVO.getSkuId());
            if(spuId != null){
                for (SpuAndSkuTO.SpuInfoEntity spuInfoEntity : spuBySkuIdListData.getSpuInfoEntity()) {
                    if(spuId.equals(spuInfoEntity.getId())){
                        orderItemEntity.setSpuId(spuId);
                        orderItemEntity.setSpuName(spuInfoEntity.getSpuName());
                        orderItemEntity.setSpuBrand(spuInfoEntity.getBrandId().toString());
                        orderItemEntity.setCategoryId(spuInfoEntity.getCatalogId());
                    }
                }
            }

            // sku 信息
            orderItemEntity.setSkuId(cartItemVO.getSkuId());
            orderItemEntity.setSkuName(cartItemVO.getSkuTitle());
            orderItemEntity.setSkuPic(cartItemVO.getSkuImg());
            orderItemEntity.setSpuPic(cartItemVO.getSkuImg());
            orderItemEntity.setSkuPrice(cartItemVO.getSkuPrice().multiply(new BigDecimal(cartItemVO.getCount())));
            orderItemEntity.setSkuQuantity(cartItemVO.getCount());
            orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItemVO.getSkuAttr(), ";"));

            // 优惠信息
            BigDecimal multiply = new BigDecimal("0");
            if(cartItemVO.getSeckillPrice() != null && cartItemVO.getSeckillCount() != null) {
                multiply = cartItemVO.getSkuPrice().subtract(cartItemVO.getSeckillPrice()).multiply(new BigDecimal(cartItemVO.getSeckillCount()));
            }
            orderItemEntity.setPromotionAmount(multiply);
            orderItemEntity.setCouponAmount(new BigDecimal("0"));
            orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
            orderItemEntity.setRealAmount(cartItemVO.getSkuPrice()
                            .multiply(new BigDecimal(orderItemEntity.getSkuQuantity()))
                    .subtract(orderItemEntity.getPromotionAmount()
                    .subtract(orderItemEntity.getCouponAmount())
                    .subtract(orderItemEntity.getIntegrationAmount())));

            // 积分信息
            List<Long> spuIdList = spuBySkuIdListData.getSpuInfoEntity().stream().map(SpuAndSkuTO.SpuInfoEntity::getId).collect(Collectors.toList());
            R spuBoundsBySpuId = couponFeignService.getSpuBoundsBySpuId(spuIdList);
            if(!spuBoundsBySpuId.isOk()){
                return null;
            }
            List<SpuBoundsTO> spuBoundsBySpuIdData = spuBoundsBySpuId.getData(new TypeReference<List<SpuBoundsTO>>() {});
            if(spuId != null) {
                orderItemEntity.setGiftGrowth(0);
                orderItemEntity.setGiftIntegration(0);
                for (SpuBoundsTO bounds : spuBoundsBySpuIdData) {
                    if (spuId.equals(bounds.getSpuId())) {
                        orderItemEntity.setGiftIntegration(bounds.getBuyBounds().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())).intValue());
                        orderItemEntity.setGiftGrowth(bounds.getGrowBounds().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())).intValue());
                    }
                }
            }

            orderItemEntityList.add(orderItemEntity);

        }

        return orderItemEntityList;
    }

//    @RabbitHandler
//    public void Test1(OrderEntity orderEntity, @Headers Message headers, Channel channel) throws IOException {
//        long deliveryTag = headers.getMessageProperties().getDeliveryTag();
//        System.out.println(deliveryTag);
//        if(deliveryTag %3 == 0){
//            channel.basicAck(deliveryTag, false);
//        }else{
//            channel.basicNack(deliveryTag, false, true);
//        }
//    }
//
//    @RabbitHandler(isDefault = true)
//    public void Test2(){
//        System.out.println("错误");
//    }

}
